package exam;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;

@WebServlet(name = "RecordServlet", value = "/RecordServlet")
public class RecordServlet extends HttpServlet {

    private HashMap<String, String> mapAnswer;

    protected void generateAnswerMap(HttpServletRequest request, Enumeration<String> pns) {
        mapAnswer = new HashMap<>();
        while (pns.hasMoreElements()) {
            String key = pns.nextElement();
            String value = request.getParameter(key);
            mapAnswer.put(key, value);
        }
    }

    protected void storeAnswer() throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("../answer.txt"));
        oos.writeObject(mapAnswer);
        oos.flush();
        oos.close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Enumeration<String> pns = request.getParameterNames();
        //生成存储标准答案的map类
        generateAnswerMap(request, pns);
        //将标准答案存入硬盘
        try {
            storeAnswer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
